'use strict';

angular.module('app')
    .controller('routeUpdateController', ['$scope', '$rootScope', '$state', '$timeout','toaster',
        function($scope, $rootScope, $state, $timeout,toaster) {
        var title = "";
        if($state.includes('**.route.update')){
            title="编辑路线";
            var id = $state.params.id;
            activate(id);
        }else if($state.includes('**.route.create')){
            title="添加路线";
            setTimeout(function(){
                !$rootScope.$$phase && $scope.$apply();
            },300);
        }
        $scope.title = $rootScope.title = title;
        $scope.loading = true;
        //初始化验证
        $scope.submit= function(){
            var m = $scope.record;
            if(m){
                $scope.isDisabled = true;//提交disabled
                var maxNum = $scope.record.maxNum;
                if(maxNum<0 || maxNum>=1000){
					$scope.alertModal({"content":"最大队伍数只能输入0~999之间"});
                	$scope.isDisabled = false;
                	return ;
                }
                var maxPeopleNum = $scope.record.maxPeopleNum;
                if(maxPeopleNum<0 || maxPeopleNum>=1000){
					$scope.alertModal({"content":"最大参赛人数只能输入0~999之间"});
                	$scope.isDisabled = false;
                	return ;
                }
                $.ajax({
    				url : $scope.record.id ? $scope.app.project_name+'/route/update' : $scope.app.project_name+'/route/add',
    				data: $scope.record
    			}).then(callback);
            }
            function callback(result) {
                if(result.httpCode ==200){//成功
                    toaster.clear('*');
                    toaster.pop('success', '', "保存成功");
                    $timeout(function(){
                        $state.go('main.funScenes.route.list');
                    },2000);
                }else if(result.httpCode ==409){
                	$scope.alertModal({"content":"路线名称已重复！"});
                	$scope.isDisabled = false;
                }else{
                    toaster.clear('*');
                    toaster.pop('error', '', result.msg);
                    $scope.isDisabled = false;
                }
            }
        }

        // 初始化页面
        function activate(id) {
	        $scope.loading = true;
        	$.ajax({
				url : $scope.app.project_name+'/route/read/detail',
				data: {'id': id}
			}).then(function(result) {
		        $scope.loading = false;
				if (result.httpCode == 200) {
					$scope.record = result.data;
				} else {
					$scope.msg = result.msg;
				}
				$scope.$apply();
			});
        }

    }]);

